package com.ifnk.portaljava.hlyt.dao.impl;

import com.ifnk.portaljava.dapWeb.advance.DBAccess;
import com.ifnk.portaljava.hlyt.dao.IDeviceLookupJdbcDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DeviceLookupJdbcDaoImpl implements IDeviceLookupJdbcDao {

	public void save(String source, String name, Connection conn)
			throws Exception {
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String hasSql = "SELECT COUNT(*) FROM device_lookup WHERE source=?";
		pstmt = conn.prepareStatement(hasSql);
		pstmt.setString(1, source);
		rs = pstmt.executeQuery();
		if (rs.next()) {
			if(rs.getInt(1) > 0){
				throw new Exception("the column 'source' "+source+" is exists!");
			}
		}
		try {
			conn.setAutoCommit(false);
			String sql = "INSERT INTO device_lookup(source,name) VALUES(?,?)";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, source);
			pstmt.setString(2, name);
			pstmt.execute();
		} catch (SQLException e) {
			e.printStackTrace();
			throw new Exception("save log error!");
		} finally {
			try {
				if (pstmt != null) {
					pstmt.close();
				}
				if (rs != null) {
					rs.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public List<String> findByName(String name) throws Exception {
		DBAccess db = new DBAccess();
		String querySql = "SELECT source FROM device_lookup WHERE name='" + name +"'";
		System.out.println("querySql:" + querySql);
		ResultSet rs = db.queryTable(querySql);
		List<String> sourceList = new ArrayList<String>();
		try {
			while (rs.next()) {
				sourceList.add(rs.getString("source"));
			}
		} catch (SQLException e) {
			throw new Exception("find source by name error!");
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		return sourceList;
	}

	public String findDeviceName(String source) throws Exception {
		String querySql = "SELECT name FROM device_lookup WHERE source='" + source+"'";
		System.out.println("querySql:" + querySql);
		String name = null;
		try {
			 name =  DBAccess.queryAValue(querySql);
		} catch (Exception e) {
			throw e;
		}
		return name;
	}

	@Override
	public void init() {
		
	}



}
